package com.talent.jiwen_teacher;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.talent.jiwen_teacher.base.BaseActivity;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.SmsResult;
import com.talent.jiwen_teacher.http.result.TeacherRegsterBean;
import com.talent.jiwen_teacher.my.WebShowActivity;
import com.talent.jiwen_teacher.util.AMUtils;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;
import com.talent.jiwen_teacher.util.downtime.DownTimer;
import com.talent.jiwen_teacher.util.downtime.DownTimerListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

import static com.talent.jiwen_teacher.CertificationInfoActivity.TEACHER_IDENTITY;
import static com.talent.jiwen_teacher.my.WebShowActivity.IS_SERVICE_RIGHT;
import static com.talent.jiwen_teacher.util.Constant.REGISTER_CODE_METHOD;


/**
 * Created by qyqx on 16/2/2.
 * 老师注册
 */
@SuppressWarnings("deprecation")
public class TeacherRegisterdActivity extends BaseActivity implements View.OnClickListener, DownTimerListener {

    private EditText mPhone, mCode, mPassword1, edt_invitation;
    private Button mGetCode, mOK;
    private String phone,code,pwd;

    @BindView(R.id.iv_new_hide)
    ImageView mIvNew;
    @BindView(R.id.rl_identity)
    RelativeLayout rl_identity;

    @BindView(R.id.txt_sex)
    TextView txt_sex;

    @BindView(R.id.txt_agree)
    TextView txt_agree;


    @BindView(R.id.txt_protocol)
    TextView txt_protocol;

    boolean isHide=true;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_teacher_register;
    }

    @Override
    public String titleName() {
        return "注册";
    }

    @Override
    protected void initData() {
//        StatusBarUtil.setTranslucent(this);
//        setHeadVisibility(View.GONE);
        initView();
    }


    private void initView() {
        mPhone = (EditText) findViewById(R.id.forget_phone);
        mCode = (EditText) findViewById(R.id.forget_code);
        mPassword1 = (EditText) findViewById(R.id.forget_password);
        edt_invitation = (EditText) findViewById(R.id.edt_invitation);
        mGetCode = (Button) findViewById(R.id.forget_getcode);
        mOK = (Button) findViewById(R.id.forget_button);
        mGetCode.setOnClickListener(this);
        mOK.setOnClickListener(this);
        mIvNew.setOnClickListener(this);
        txt_protocol.setOnClickListener(this);
        rl_identity.setOnClickListener(this);
        mPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    if (AMUtils.isMobile(s.toString().trim())) {
                        phone = mPhone.getText().toString().trim();
                        mGetCode.setClickable(true);
                        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
                        AMUtils.onInactive(mContext, mPhone);
                    } else {
                        Toast.makeText(mContext, R.string.Illegal_phone_number, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    mGetCode.setClickable(false);
                    mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 4) {
                    AMUtils.onInactive(mContext, mCode);
                        mOK.setClickable(true);
                        mOK.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    DownTimer downTimer;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.forget_getcode:
                if (TextUtils.isEmpty(mPhone.getText().toString().trim())) {
                    showToast(getString(R.string.phone_number_is_null));
                } else {
                    downTimer = new DownTimer();
                    downTimer.setListener(this);
                    downTimer.startDown(60 * 1000);
                    sendCode();
                }
                break;
            case R.id.forget_button:
                if (TextUtils.isEmpty(mPhone.getText().toString())) {
                    showToast(getString(R.string.phone_number_is_null));
//                    mPhone.setShakeAnimation();
                    return;
                }

                if (TextUtils.isEmpty(mCode.getText().toString())) {
                    showToast(getString(R.string.code_is_null));
//                    mCode.setShakeAnimation();
                    return;
                }

                if (TextUtils.isEmpty(mPassword1.getText().toString())) {
                    showToast(getString(R.string.password_is_null));
//                    mPassword1.setShakeAnimation();
                    return;
                }

                if (mPassword1.length() < 6 || mPassword1.length() > 16) {
                    showToast(getString( R.string.passwords_invalid));
                    return;
                }

                if(identity==-1){
                    showToast(getString( R.string.choose_identity));
                    return;
                }

                if(!isAgree){
                    showToast("请先同意《即问服务协议》");
                    return;
                }

                phone=mPhone.getText().toString().trim();
                code=mCode.getText().toString().trim();
                pwd=mPassword1.getText().toString().trim();
                register();
                break;

            case R.id.iv_new_hide:
                String pwd1=mPassword1.getText().toString().trim();
                isHide = !isHide;
                if (isHide) {
                    mIvNew.setImageResource(R.mipmap.forgetpwd_hide);
                    mPassword1.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }else {
                    mIvNew.setImageResource(R.mipmap.forgetpwd_show);
                    mPassword1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }

                if(!Validators.isEmpty(pwd1)){
                    mPassword1.setSelection(pwd1.length());
                }

                break;
            case R.id.rl_identity:
                showWheelPicker(new ArrayList<String>(Arrays.asList("在职名师","名校学霸")),null);
                break;
            case R.id.txt_protocol:
                IS_SERVICE_RIGHT=1;
                WebShowActivity.WEB_SHOW_TYPE=WebShowActivity.WEB_XIE_TYPE;
//                intentActivity(WebShowActivity.class);
                Intent intent=new Intent(TeacherRegisterdActivity.this,WebShowActivity.class);
                startActivityForResult(intent,101);
                break;
        }
    }


    private int identity=-1;//1老师2学生

    /**
     * 滚轮选择
     *
     * @param pickerList
     */
    private void showWheelPicker(final List<String> pickerList, final String str) {
        List<String> showList = new ArrayList<>();
        int selectPosition = 0;
        for (int i = 0; i < pickerList.size(); i++) {
            showList.add(pickerList.get(i));
            if (null != str){
                if (str.equals( pickerList.get(i))) {
                    selectPosition = i;
                }
            }
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(TeacherRegisterdActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                identity=options1+1;
                txt_sex.setText(pickerList.get(options1));
            }
        }).setSubmitColor(ContextCompat.getColor(this , R.color.common_app_color))
                .setCancelColor(ContextCompat.getColor(this , R.color.text_gray_6)).build();
        pvOptions.setPicker(showList);

        if (null != str) {
            pvOptions.setSelectOptions(selectPosition);
        }
        pvOptions.show();
    }


    private void sendCode() {
        Map<String, String> map = new HashMap<>();
        map.put("method", REGISTER_CODE_METHOD);
        map.put("phone", mPhone.getText().toString().trim());
        Observable observable = ApiFactory.getEducationApiSingleton().sendMsg(map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<SmsResult>(this) {
            @Override
            protected void _onNext(SmsResult smsResult) {
//                if (smsResult != null) {
//                    String code = smsResult.getVcode();
//                    if (Validators.isEmpty(code)) {
//                        showToast(getString(R.string.code_get_fill));
//                        downTimer.stopDown();
//                        mGetCode.setText(R.string.get_code);
//                        mGetCode.setClickable(true);
//                        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
//                    }
//                } else {
//                    showToast(getString(R.string.data_is_wrong));
//                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                downTimer.stopDown();
                mGetCode.setText(R.string.get_code);
                mGetCode.setClickable(true);
                mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }



    private void register() {

        String inviteCode = edt_invitation.getText().toString().trim();

        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("password", pwd);
        map.put("vCode", code);
        map.put("inviteCode", inviteCode == null ? "" : inviteCode);
        map.put("teacherType", ""+identity);
        Observable observable = ApiFactory.getEducationApiSingleton().teacherRegister(map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<TeacherRegsterBean>(this) {
            @Override
            protected void _onNext(TeacherRegsterBean teacherRegsterBean) {
                if(teacherRegsterBean!=null && !Validators.isEmpty(teacherRegsterBean.getTeacherId())){
                    SPUtil.stringIn(SPConstant.USER_ID,teacherRegsterBean.getTeacherId());
                    SPUtil.stringIn(SPConstant.PHONE,phone);
                    SPUtil.stringIn(SPConstant.PASSWORD,pwd);
                    SPUtil.intIn(SPConstant.TEACHER_IDENTITY,identity);
                    Intent intent=new Intent(TeacherRegisterdActivity.this,CertificationInfoActivity.class);
                    intent.putExtra(TEACHER_IDENTITY,identity);
                    startActivity(intent);
//                    intentActivity(CertificationInfoActivity.class);
                }else{
                    showToast("数据有误请稍后重试");
                }


            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }




    @Override
    public void onTick(long millisUntilFinished) {
        mGetCode.setText( String.valueOf(millisUntilFinished / 1000)+"s");
        mGetCode.setClickable(false);
        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_gray));
    }

    @Override
    public void onFinish() {
        mGetCode.setText(R.string.get_code);
        mGetCode.setClickable(true);
        mGetCode.setBackgroundDrawable(getResources().getDrawable(R.drawable.rs_select_btn_blue));
    }

    private boolean isAgree=false;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==1001){
            isAgree=true;
            txt_agree.setText("用户已同意");
        }
    }
}
